/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package com.endpoint.websocket.encoder;

import com.endpoint.websocket.util.SigEscenario;
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.StringWriter;
import javax.imageio.ImageIO;
import javax.json.Json;
import javax.json.stream.JsonGenerator;
import javax.websocket.EncodeException;
import javax.websocket.Encoder;
import javax.websocket.EndpointConfig;

/**
 *
 * @author MoisesAntonio
 */
public class EncSigEscenario implements Encoder.Text<SigEscenario>
{

    @Override
    public String encode(SigEscenario object) throws EncodeException {
        
        StringWriter swriter = new StringWriter();
        try (JsonGenerator jsonGen = Json.createGenerator(swriter)) {
            // Creamos un buffer image.
            BufferedImage bimage = new BufferedImage(object.getI().getWidth(null), object.getI().getHeight(null), BufferedImage.TYPE_INT_ARGB);

            // Pasamos la imágen al Buffer.
            Graphics2D bGr = bimage.createGraphics();
            bGr.drawImage(object.getI(), 0, 0, null);
            bGr.dispose();
			    
            //Y del buffer al array.
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write( bimage, "png", baos );
            baos.flush();
            byte[] imageInByte = baos.toByteArray();
            baos.close();
            
            //Esto se queda como está que es como codificar la imagen.
            String encodedImage = Base64.encode(imageInByte);
            
            jsonGen.writeStartObject()
                .write("escenario", encodedImage)
            .writeEnd();
        } catch (IOException ex) {
            //Logger.getLogger(EncEscenario.class.getName()).log(Level.SEVERE, null, ex);
        }
        
        return swriter.toString();
    }

    @Override
    public void init(EndpointConfig config) {    }

    @Override
    public void destroy() {    }
    
}
